 //
//  BDAlertView.h
//  BDAlertViewDemo
//
//  Created by Jaesun on 17/1/4.
//  Copyright © 2017年 S.J. All rights reserved.
//

#import "BDAlertView.h"

#import "BDAlertViewDefaultCell.h"
#import "BDAlertViewSubTitleCell.h"
#import "Masonry.h"


@interface BDAlertViewStack : NSObject

@property (nonatomic) NSMutableArray *alertViews;

+ (BDAlertViewStack *)sharedInstance;

- (void)push:(BDAlertView *)alertView;
- (void)pop:(BDAlertView *)alertView;

@end

static const CGFloat AlertViewWidth = 280.0;
static const CGFloat AlertViewContentMargin = 9;
static const CGFloat AlertViewVerticalElementSpace = 10;
static const CGFloat AlertViewItemHeight = 44;
static const CGFloat AlertViewLineLayerWidth = 0.5;
static const CGFloat AlertViewVerticalEdgeMinMargin = 25;

@interface BDAlertView ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UIWindow *mainWindow;
@property (nonatomic) UIWindow *alertWindow;
@property (nonatomic) UIView *backgroundView;
@property (nonatomic) UIView *alertView;
@property (nonatomic) UILabel *titleLabel;
@property (nonatomic) UIView *contentView;
@property (nonatomic) UIScrollView *messageScrollView;
@property (nonatomic) UILabel *messageLabel;
@property (nonatomic) CALayer *verticalLine;
@property (nonatomic) UITapGestureRecognizer *tap;


@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSArray<NSString *> *otherTitles;

@property (nonatomic, strong) NSArray<NSString *> *subTitles;

@property (nonatomic, assign)NSIndexPath *selIndex;
@property (nonatomic, assign)BOOL ischioce;  // 是否多选
@property (nonatomic, assign) BDAlertViewContentType alertViewContentType;


@end

@implementation BDAlertView

- (UIWindow *)windowWithLevel:(UIWindowLevel)windowLevel
{
	NSArray *windows = [[UIApplication sharedApplication] windows];
	for (UIWindow *window in windows) {
		if (window.windowLevel == windowLevel) {
			return window;
		}
	}
	return nil;
}

- (id)initWithTitle:(NSString *)title
        otherTitles:(NSArray<NSString *> *)otherTitles subTitles:(NSArray<NSString *> *)subTitles
         completion:(BDAlertViewCompletionBlock)completion {
    
    if (otherTitles.count != 0) {
        
        self.otherTitles = otherTitles;
        self.subTitles = subTitles;
        CGFloat tableViewHeight = 0;
        
        for (NSString *title in otherTitles) {
        
            CGFloat titleHeight = [self heightForString:title withWidth:180];
            
            if (AlertViewItemHeight < titleHeight) {
                titleHeight = titleHeight;
            }
            else {
                titleHeight = AlertViewItemHeight;
            }
            tableViewHeight += titleHeight;
        }
        
        if (6 < otherTitles.count) {
            tableViewHeight = AlertViewItemHeight * 6;
        }
        
        self.alertViewContentType = BDAlertViewContentTypeSubTitle;
        
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 260, tableViewHeight) style:(UITableViewStyleGrouped)];
        self.tableView.backgroundColor = [UIColor whiteColor];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        if (@available(iOS 11.0, *)) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
    }
    
    return [self initWithTitle:title message:nil contentView:self.tableView completion:completion];
}


- (id)initWithTitle:(NSString *)title
           ischioce:(BOOL)ischioce
        otherTitles:(NSArray<NSString *> *)otherTitles
         completion:(BDAlertViewCompletionBlock)completion {
    self.ischioce = ischioce;
    if (otherTitles.count != 0) {
        
        self.otherTitles = otherTitles;
        CGFloat tableViewHeight = 0;
        
        for (NSString *title in otherTitles) {
            CGFloat titleHeight = [self heightForString:title withWidth:250];
            if (AlertViewItemHeight < titleHeight) {
                titleHeight = titleHeight;
            }
            else {
                titleHeight = AlertViewItemHeight;
            }
            tableViewHeight += titleHeight;
        }
        
        if (6 < otherTitles.count) {
            tableViewHeight = AlertViewItemHeight * 6;
        }
        self.alertViewContentType = BDAlertViewContentTypeDefault;
        
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 260, tableViewHeight) style:(UITableViewStyleGrouped)];
        self.tableView.backgroundColor = [UIColor whiteColor];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
    }
    
    return [self initWithTitle:title message:nil contentView:self.tableView completion:completion];
}


- (id)initWithTitle:(NSString *)title
			message:(NSString *)message
		contentView:(UIView *)contentView
		 completion:(BDAlertViewCompletionBlock)completion
{
	self = [super init];
	if (self) {
		self.mainWindow = [self windowWithLevel:UIWindowLevelNormal];
		
		self.alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
		self.alertWindow.windowLevel = UIWindowLevelAlert;
		self.alertWindow.backgroundColor = [UIColor clearColor];
		self.alertWindow.rootViewController = self;
		
		CGRect frame = [self frameForOrientation];
		self.view.frame = frame;
		
		self.backgroundView = [[UIView alloc] initWithFrame:frame];
		self.backgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.25];
		self.backgroundView.alpha = 0;
		[self.view addSubview:self.backgroundView];
		
		self.alertView = [[UIView alloc] init];
		self.alertView.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
		self.alertView.layer.cornerRadius = 8.0;
		self.alertView.layer.opacity = .95;
		self.alertView.clipsToBounds = YES;
		[self.view addSubview:self.alertView];
		
		// Title
		self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(AlertViewContentMargin,
																	2 *AlertViewVerticalElementSpace,
																	AlertViewWidth - AlertViewContentMargin*2,
																	44)];
		self.titleLabel.text = title;
		self.titleLabel.backgroundColor = [UIColor clearColor];
		self.titleLabel.textColor = [UIColor blackColor];
		self.titleLabel.textAlignment = NSTextAlignmentCenter;
		self.titleLabel.font = [UIFont boldSystemFontOfSize:17];
		self.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
		self.titleLabel.numberOfLines = 0;
		self.titleLabel.frame = [self adjustLabelFrameHeight:self.titleLabel];
		[self.alertView addSubview:self.titleLabel];
        
        [self.titleLabel addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectJiegou)]];
        
        
		CGFloat messageLabelY = self.titleLabel.frame.origin.y + self.titleLabel.frame.size.height + AlertViewVerticalElementSpace;
		
		// Optional Content View
		if (contentView) {
			self.contentView = contentView;
			self.contentView.frame = CGRectMake(0,
												messageLabelY,
												self.contentView.frame.size.width,
												self.contentView.frame.size.height);
			self.contentView.center = CGPointMake(AlertViewWidth/2, self.contentView.center.y);
			[self.alertView addSubview:self.contentView];
			messageLabelY += contentView.frame.size.height;
		}
		
		// Message
		self.messageScrollView = [[UIScrollView alloc] initWithFrame:(CGRect){
			AlertViewContentMargin,
			messageLabelY,
			AlertViewWidth - AlertViewContentMargin*2,
			44}];
		self.messageScrollView.scrollEnabled = YES;
		
		self.messageLabel = [[UILabel alloc] initWithFrame:(CGRect){0, 0,
			self.messageScrollView.frame.size}];
		self.messageLabel.text = message;
		self.messageLabel.backgroundColor = [UIColor clearColor];
		self.messageLabel.textColor = [UIColor whiteColor];
		self.messageLabel.textAlignment = NSTextAlignmentCenter;
		self.messageLabel.font = [UIFont systemFontOfSize:15];
		self.messageLabel.lineBreakMode = NSLineBreakByWordWrapping;
		self.messageLabel.numberOfLines = 0;
		self.messageLabel.frame = [self adjustLabelFrameHeight:self.messageLabel];
		self.messageScrollView.contentSize = self.messageLabel.frame.size;
        
		
		[self.messageScrollView addSubview:self.messageLabel];
		[self.alertView addSubview:self.messageScrollView];
        

       
		// Get total item height
		CGFloat totalBottomHeight = AlertViewLineLayerWidth;
	
        totalBottomHeight += AlertViewItemHeight;
	
		
		self.messageScrollView.frame = (CGRect) {
			self.messageScrollView.frame.origin,
			self.messageScrollView.frame.size.width,
			MIN(self.messageLabel.frame.size.height, self.alertWindow.frame.size.height - self.messageScrollView.frame.origin.y - totalBottomHeight - AlertViewVerticalEdgeMinMargin * 2)
		};
		
		// Line
		CALayer *lineLayer = [self lineLayer];
		lineLayer.frame = CGRectMake(0, self.messageScrollView.frame.origin.y + self.messageScrollView.frame.size.height + AlertViewVerticalElementSpace, AlertViewWidth, AlertViewLineLayerWidth);
		[self.alertView.layer addSublayer:lineLayer];
	
		self.alertView.bounds = CGRectMake(0, 0, AlertViewWidth, 150);
		
		if (completion) {
			self.completion = completion;
		}
		
		[self resizeViews];
		
		self.alertView.center = [self centerWithFrame:frame];
		
		[self setupGestures];
		
		if ((self = [super init])) {
			NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
			[center addObserver:self selector:@selector(keyboardWillShown:) name:UIKeyboardWillShowNotification object:nil];
			[center addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
		}
		return self;
	}
	return self;
}

// 多选方法
- (void)selectJiegou{
    [self dismiss];
}

- (id)initWithContentView:(UIView *)contentView completion:(BDAlertViewCompletionBlock)completion {
    self = [super init];
    if (self) {
        self.mainWindow = [self windowWithLevel:UIWindowLevelNormal];
        
        self.alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        self.alertWindow.windowLevel = UIWindowLevelAlert;
        self.alertWindow.backgroundColor = [UIColor clearColor];
        self.alertWindow.rootViewController = self;
        
        CGRect frame = [self frameForOrientation];
        self.view.frame = frame;
        
        self.backgroundView = [[UIView alloc] initWithFrame:frame];
        self.backgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.25];
        self.backgroundView.alpha = 0;
        [self.view addSubview:self.backgroundView];
        
        self.alertView = contentView;
        
        [self.view addSubview:self.alertView];
        
        if (completion) {
            self.completion = completion;
        }
        else {
            self.completion = ^(BOOL cancel,NSInteger selectIndex){
            };
        }
        self.alertView.center = [self centerWithFrame:frame];
        
        [self setupGestures];
        
        if ((self = [super init])) {
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center addObserver:self selector:@selector(keyboardWillShown:) name:UIKeyboardWillShowNotification object:nil];
            [center addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        }
        return self;
    }
    return self;
}


- (void)keyboardWillShown:(NSNotification*)notification
{
	if(self.isVisible) {
        CGRect keyboardFrameBeginRect = [[[notification userInfo] valueForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
		if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8 && (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight)) {
			keyboardFrameBeginRect = (CGRect){keyboardFrameBeginRect.origin.y, keyboardFrameBeginRect.origin.x, keyboardFrameBeginRect.size.height, keyboardFrameBeginRect.size.width};
		}
		CGRect interfaceFrame = [self frameForOrientation];
		
		if(interfaceFrame.size.height -  keyboardFrameBeginRect.size.height <= _alertView.frame.size.height + _alertView.frame.origin.y)
		{
			[UIView animateWithDuration:.35 delay:0 options:0x70000 animations:^(void)
			 {
				 _alertView.frame = (CGRect){_alertView.frame.origin.x, interfaceFrame.size.height - keyboardFrameBeginRect.size.height - _alertView.frame.size.height - 20, _alertView.frame.size};
			 } completion:nil];
		}
	}
}

- (void)keyboardWillHide:(NSNotification*)notification
{
	if(self.isVisible)
	{
		[UIView animateWithDuration:.35 delay:0 options:0x70000 animations:^(void)
		 {
			 _alertView.center = [self centerWithFrame:[self frameForOrientation]];
		 } completion:nil];
	}
}

- (CGRect)frameForOrientation
{
	UIWindow *window = [[UIApplication sharedApplication].windows count] > 0 ? [[UIApplication sharedApplication].windows objectAtIndex:0] : nil;
	if (!window)
		window = [UIApplication sharedApplication].keyWindow;
	if([[window subviews] count] > 0)
	{
		return [[[window subviews] objectAtIndex:0] bounds];
	}
	return [[self windowWithLevel:UIWindowLevelNormal] bounds];
}

- (CGRect)adjustLabelFrameHeight:(UILabel *)label
{
	CGFloat height;
	
	if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
		CGSize size = [label.text sizeWithFont:label.font
							 constrainedToSize:CGSizeMake(label.frame.size.width, FLT_MAX)
								 lineBreakMode:NSLineBreakByWordWrapping];
		
		height = size.height;
#pragma clang diagnostic pop
	} else {
		NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
		context.minimumScaleFactor = 1.0;
		CGRect bounds = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, FLT_MAX)
												 options:NSStringDrawingUsesLineFragmentOrigin
											  attributes:@{NSFontAttributeName:label.font}
												 context:context];
		height = bounds.size.height;
	}
	
	return CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width, height);
}


- (CGPoint)centerWithFrame:(CGRect)frame
{
	return CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame) - [self statusBarOffset]);
}

- (CGFloat)statusBarOffset
{
	CGFloat statusBarOffset = 0;
	if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
		statusBarOffset = 20;
	}
	return statusBarOffset;
}

- (void)setupGestures
{
    if (!self.ischioce) {
        self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss:)];
        [self.tap setNumberOfTapsRequired:1];
        [self.backgroundView setUserInteractionEnabled:YES];
        [self.backgroundView setMultipleTouchEnabled:NO];
        [self.backgroundView addGestureRecognizer:self.tap];
    }
}

- (void)resizeViews
{
	CGFloat totalHeight = 0;
	for (UIView *view in [self.alertView subviews]) {
		if ([view class] != [UIButton class]) {
			totalHeight += view.frame.size.height + AlertViewVerticalElementSpace;
		}
	}
	
	totalHeight += AlertViewVerticalElementSpace;
	
	self.alertView.frame = CGRectMake(self.alertView.frame.origin.x,
									  self.alertView.frame.origin.y,
									  self.alertView.frame.size.width,
									  MIN(totalHeight, self.alertWindow.frame.size.height));
}


- (void)show
{
	[[BDAlertViewStack sharedInstance] push:self];
}

- (void)showInternal
{
	[self.alertWindow addSubview:self.view];
	[self.alertWindow makeKeyAndVisible];
	self.visible = YES;
	[self showBackgroundView];
	[self showAlertAnimation];
}

- (void)showBackgroundView
{
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
		self.mainWindow.tintAdjustmentMode = UIViewTintAdjustmentModeDimmed;
		[self.mainWindow tintColorDidChange];
	}
	[UIView animateWithDuration:0.3 animations:^{
		self.backgroundView.alpha = 1;
	}];
}

- (void)hide
{
	[self.view removeFromSuperview];
}

- (void)dismiss
{
	[self dismiss:nil];
}

- (void)dismiss:(id)sender
{
	[self dismiss:sender animated:YES];
}

- (void)dismiss:(id)sender animated:(BOOL)animated
{
	self.visible = NO;
	
	[UIView animateWithDuration:(animated ? 0.2 : 0) animations:^{
		self.alertView.alpha = 0;
		self.alertWindow.alpha = 0;
	} completion:^(BOOL finished) {
		
        if (self.completion) {
			
            BOOL cancelled = NO;
			NSInteger selectedIndex = -1;
		
			if (sender) {
				self.completion(cancelled, selectedIndex);
			}
		}
		
		if ([[[BDAlertViewStack sharedInstance] alertViews] count] == 1) {
			if (animated) {
				[self dismissAlertAnimation];
			}
			if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
				self.mainWindow.tintAdjustmentMode = UIViewTintAdjustmentModeAutomatic;
				[self.mainWindow tintColorDidChange];
			}
			[UIView animateWithDuration:(animated ? 0.2 : 0) animations:^{
				self.backgroundView.alpha = 0;
				[self.alertWindow setHidden:YES];
				[self.alertWindow removeFromSuperview];
				self.alertWindow.rootViewController = nil;
				self.alertWindow = nil;
			} completion:^(BOOL finished) {
				// [self.mainWindow makeKeyAndVisible];
			}];
		}
		
		[[BDAlertViewStack sharedInstance] pop:self];
	}];
}

- (void)showAlertAnimation
{
	CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
	
	animation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1)],
						 [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.05, 1.05, 1)],
						 [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1)]];
	animation.keyTimes = @[ @0, @0.5, @1 ];
	animation.fillMode = kCAFillModeForwards;
	animation.removedOnCompletion = NO;
	animation.duration = .3;
	
	[self.alertView.layer addAnimation:animation forKey:@"showAlert"];
}

- (void)dismissAlertAnimation
{
	CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
	
	animation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1)],
						 [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.95, 0.95, 1)],
						 [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1)]];
	animation.keyTimes = @[ @0, @0.5, @1 ];
	animation.fillMode = kCAFillModeRemoved;
	animation.duration = .2;
	
	[self.alertView.layer addAnimation:animation forKey:@"dismissAlert"];
}

- (CALayer *)lineLayer
{
	CALayer *lineLayer = [CALayer layer];
	lineLayer.backgroundColor = [[UIColor colorWithWhite:0.90 alpha:0.3] CGColor];
	return lineLayer;
}

#pragma mark- 
#pragma mark UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.otherTitles.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.alertViewContentType == BDAlertViewContentTypeSubTitle) {
        
        BDAlertViewSubTitleCell *cell = [[BDAlertViewSubTitleCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"BDAlertViewSubTitleCell"];
        cell.title = self.otherTitles[indexPath.row];
        cell.subTitle = self.subTitles[indexPath.row];
        return cell;
        
    }
    else if (self.alertViewContentType == BDAlertViewContentTypeDefault) {
        BDAlertViewDefaultCell *cell = [[BDAlertViewDefaultCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"BDAlertViewDefaultCell"];
        cell.title = self.otherTitles[indexPath.row];
        return cell;
        
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    if (self.ischioce) {
//        //记录当前选中的位置索引
//        _selIndex = indexPath;
//        //当前选择的打勾
//        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//        if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
//            cell.accessoryType = UITableViewCellAccessoryNone;
//        }
//        else{
//            cell.accessoryType = UITableViewCellAccessoryCheckmark;
//        }
//    }
    
    if (self.completion) {
        self.completion(YES, indexPath.row);
    }
//    if (!self.ischioce) {
        [self dismiss];
//    }
}

// ios11变形返还空视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat heightForRow = 0;
    if (self.alertViewContentType == BDAlertViewContentTypeDefault) {
        heightForRow = [self heightForString:self.otherTitles[indexPath.row] withWidth:250];
    }
    else if (self.alertViewContentType == BDAlertViewContentTypeSubTitle) {
        heightForRow =
        [self heightForString:self.otherTitles[indexPath.row] withWidth:180];
    }
    if (AlertViewItemHeight < heightForRow) {
       return heightForRow;
    }
    return AlertViewItemHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001f;
}



#pragma mark -
#pragma mark UIViewController

- (BOOL)prefersStatusBarHidden
{
	return [UIApplication sharedApplication].statusBarHidden;
}

- (BOOL)shouldAutorotate
{
	return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
	return UIInterfaceOrientationMaskAll;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return YES;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
{
	CGRect frame = [self frameForOrientation];
	self.backgroundView.frame = frame;
	self.alertView.center = [self centerWithFrame:frame];
}

#pragma mark -
#pragma mark Public

+ (instancetype)showAlertWithContentView:(UIView *)contentView completion:(BDAlertViewCompletionBlock)completion {
    
    BDAlertView *alertView = [[self alloc] initWithContentView:contentView completion:completion];
    [alertView show];
    return alertView;
}

+ (instancetype)showAlertWithTitle:(NSString *)title
						   message:(NSString *)message
					   contentView:(UIView *)view
						completion:(BDAlertViewCompletionBlock)completion
{
	BDAlertView *alertView = [[self alloc] initWithTitle:title
												 message:message
											 contentView:view
											  completion:completion];
	[alertView show];
	return alertView;
}


+ (instancetype)showAlertWithTitle:(NSString *)title
                          isChoice:(BOOL)isChoice
                          otherTitles:(NSArray<NSString *> *)otherTitles
                          completion:(BDAlertViewCompletionBlock)completion
{
    
    BDAlertView *alertView = [[self alloc] initWithTitle:title ischioce:isChoice otherTitles:otherTitles completion:completion];
    [alertView show];
    return alertView;
}


+ (instancetype)showAlertWithTitle:(NSString *)title
                       otherTitles:(NSArray<NSString *> *)otherTitles subTitles:(NSArray<NSString *> *)subTitles
                         completion:(BDAlertViewCompletionBlock)completion
{
    
    
    BDAlertView *alertView = [[self alloc] initWithTitle:title otherTitles:otherTitles subTitles:subTitles completion:completion];
    
    [alertView show];
    return alertView;
}


- (void)setTapToDismissEnabled:(BOOL)enabled
{
	self.tap.enabled = enabled;
}

#pragma mark - 自定义方法
- (CGFloat)heightForString:(NSString *)str withWidth:(CGFloat)width {
    
    CGRect rect = [str boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.f]} context:nil];
    return rect.size.height;
}



#pragma mark- 系统AlertViewController 封装

- (void)alertViewTo:(UIViewController *)controller title:(NSString *)title message:(NSString *)message cancelTitle:(NSString *)cancelTitle completion:(BDAlertViewCompletionBlock)completion {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        if (completion) {
            self.completion(YES,0);
        }
    }];
    
    [alert addAction:cancelAction];
    [controller presentViewController:alert animated:YES completion:nil];
}

- (void)alertViewTo:(UIViewController *)controller title:(NSString *)title message:(NSString *)message cancelTitle:(NSString *)cancelTitle sureTitle:(NSString *)sureTitle completion:(BDAlertViewCompletionBlock)completion {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction *YESAction = [UIAlertAction actionWithTitle:sureTitle style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if (completion) {
            self.completion(YES,1);
        }
        
    }];
    
    UIAlertAction *NOAction = [UIAlertAction actionWithTitle:cancelTitle style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        if (completion) {
            self.completion(NO,0);
        }
    }];
    [alert addAction:YESAction];
    [alert addAction:NOAction];
    
    [controller presentViewController:alert animated:YES completion:nil];
}


@end

@implementation BDAlertViewStack

+ (instancetype)sharedInstance
{
	static BDAlertViewStack *_sharedInstance = nil;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		_sharedInstance = [[BDAlertViewStack alloc] init];
		_sharedInstance.alertViews = [NSMutableArray array];
	});
	
	return _sharedInstance;
}

- (void)push:(BDAlertView *)alertView
{
	for (BDAlertView *av in self.alertViews) {
		if (av != alertView) {
			[av hide];
		}
		else {
			return;
		}
	}
	[self.alertViews addObject:alertView];
	[alertView showInternal];
}

- (void)pop:(BDAlertView *)alertView
{
	[alertView hide];
	[self.alertViews removeObject:alertView];
	BDAlertView *last = [self.alertViews lastObject];
	if (last && !last.view.superview) {
		[last showInternal];
	}
}

@end
